<template>
    <div class="poa post_videobig upload-video-wrap">
        <title_vue :title="'发布视频'" />
        <!-- 哈哈 -->
        <div class="content">
            <div class="video-wrap">
                <video class="video" @click="togglePlay('Payer')" ref="videoPlayer">
                </video>
                <p class="video-guide" v-if="!videoUrl">点击上传或者在下方输入url,推荐使用url</p>
                <input type="file" id="file" accept="video/*" class="video-input" @change="ChangeFile" v-if="!videoUrl">
            </div>
            <div class="content-item">
                <input placeholder="请输入视频链接（如本地上传可不填）" type="text" class="input" :value="videoUrl">
            </div>
            <div class="content-item" v-if="!videoUrl">
                <input placeholder="请输入封面链接（如本地上传默认第一帧）" type="text" class="input">
            </div>
            <div class="content-item">
                <input placeholder="请输入视频描述" type="text" class="input" v-model="videoObj.videoDesc">
            </div>
            <div class="content-item">
                <div class="btn" @click="togglePlay('Preview')">预览</div>
                <div class="btn" @click="captureVideoCover">截图</div>
                <div class="btn" @click="uploadVideo">发布</div>
            </div>
            <img src="" alt="" ref="previewImage">
        </div>
    </div>
</template>
<script setup>
import { useRouter } from "vue-router";
import { reactive, ref, defineAsyncComponent } from "vue";
import { PublishVideo, UploadCover, UploadVideo } from "../api/api.js";
const title_vue = defineAsyncComponent(() => import('../components/common/title_top.vue'))
let router = useRouter()
let videoObj = reactive({
    videoDesc: ''
})
let videoUrl = ref('')
let videoPlayer = ref(null)
let previewImage = ref(null)
function back() {
    router.go(-1)
}
function ChangeFile(event) {
    videoObj.videoPath = event.target.files[0];
    if (videoObj.videoPath) {
        videoUrl.value = getObjectURL(videoObj.videoPath)
        videoPlayer.value.src = videoUrl.value
        videoPlayer.value.play()
        videoPlayer.value.addEventListener('loadeddata', captureVideoCover)
    }
}
function getObjectURL(file) {
    let url = null;
    if (window.createObjectURL !== undefined) {
        url = window.createObjectURL(file)
    } else if (window.URL !== undefined) {
        url = window.URL.createObjectURL(file)
    } else if (window.webkitURL !== undefined) {
        url = window.webkitURL.createObjectURL(file)
    }
    return url;
}
function togglePlay(discren) {
    if (discren === 'Payer') {
        videoPlayer.value.paused ? videoPlayer.value.play() : videoPlayer.value.pause()
    } else {
        videoPlayer.value.currentTime = 0
        videoPlayer.value.play()
    }
}
function captureVideoCover() {
    let canvas = document.createElement('canvas');
    canvas.width = videoPlayer.value.videoWidth
    canvas.height = videoPlayer.value.videoHeight
    canvas.getContext('2d').drawImage(videoPlayer.value, 0, 0, canvas.width, canvas.height)
    previewImage.value.src = canvas.toDataURL("image/jpg")
    videoObj.coverUrl = canvas.toDataURL("image/png")
    previewImage.value.style.display = 'block'
    setTimeout(() => {
        previewImage.value.style.display = 'none'
    }, 3000)
}
async function uploadVideo() {
    let formData = new FormData()
    console.log(videoObj)
    console.log(formData)
    formData.append('videoPath', videoObj.videoPath)
    console.log(formData)
    const { data: videoRes } = await UploadVideo(formData)
    if (videoRes) {
        console.log(videoRes)
        let filename = videoRes.filename;
        console.log(filename)
        const videoId = filename.substr(0, filename.indexOf('.'));
        let videoCover = dataURItoBlob(videoObj.coverUrl)
        let coverPic = new FormData()
        coverPic.append('videoId', videoId)
        coverPic.append('videoCover', videoCover)
        const { data: coverRes } = await UploadCover(coverPic)
        if (coverRes) {
            let MyInfo = JSON.parse(localStorage.getItem('user'));
            let userId = MyInfo?.userId || '';
            const { data: publishRes } = await PublishVideo({
                userId,
                videoDesc: videoObj.videoDesc,
            })
            if (publishRes) back()
        }
    }
}
function dataURItoBlob(dataURI) {
    const byteString = atob(dataURI.split(',')[1]);
    const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
        .1.ia[i] = byteString.charCodeAt(i)
    }
    return new Blob([ab], { type: mimeString })
}
</script>
<style scoped lang="scss">
@function r($v) {
    @return $v / (390 /10rem)
}

.upload-video-wrap {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: #161622;

    .header {
        background: #161622;

        .header_arrow {
            .arrow:before {
                content: " ";
                display: inline-block;
                -ms-transform: rotate(45deg);
                transform: rotate(45deg);
                height: .3rem;
                width: .3rem;
                border-width: 0 0 r(2) r(2);
                border-color: #fff;
                border-style: solid;
                position: relative;
                top: 0
            }
        }
    }

    .content {
        display: flex;
        flex-direction: column;

        .video-wrap {
            position: relative;
            display: flex;
            background: #000;
            align-items: center;
            justify-content: center;
            height: 50vh;

            .video {
                width: 100%;
                height: 100%;
            }

            .video-guide {
                position: absolute;
                color: white;
                margin: 0;
                font-size: r(16);
            }

            .video-input {
                position: absolute;
                left: 0;
                right: 0;
                top: 0;
                bottom: 0;
                opacity: 0;
            }
        }

        .content-item {
            position: relative;
            display: flex;
            padding: r(10) r(20);
            line-height: r(44);
            height: r(64);
            justify-content: flex-start;

            .input {
                width: 100%;
                background: #161622;
                color: #e8e8e9;
                border: none;
                font-size: r(14);
            }
        }

        .content-item:last-of-type {
            justify-content: space-around;
            align-items: center;

            .btn {
                padding: r(5);
                font-size: r(12);
                width: r(70);
                height: r(25);
                color: white;
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
    }
}

.post_videobig {
    background-color: #161622;
}
</style>